<template>
<view>
        <u-navbar title="注册" :background="background" back-icon-color="#efefef" title-color="#efefef"></u-navbar>
	<view class="wrap">
		<u-form :model="model" :rules="rules" ref="uForm" :errorType="errorType">
			<u-form-item  label-width="120" :label-position="labelPosition" label="用户名" prop="name">
				<u-input :border="border" placeholder="请输入用户名" v-model="model.name" type="text"></u-input>
			</u-form-item>
			<u-form-item :label-position="labelPosition" label="性别" prop="sex">
				<u-input :border="border" type="select" :select-open="actionSheetShow" v-model="model.sex" placeholder="请选择性别" @click="actionSheetShow = true"></u-input>
			</u-form-item>
			<u-form-item :label-position="labelPosition" label="密码" prop="password">
				<u-input :password-icon="true" :border="border" type="password" v-model="model.password" placeholder="请输入密码"></u-input>
			</u-form-item>
			<u-form-item :label-position="labelPosition" label="确认密码" label-width="150" prop="rePassword">
				<u-input :border="border" type="password" v-model="model.rePassword" placeholder="请确认密码"></u-input>
			</u-form-item>
            <u-form-item  :label-position="labelPosition" label="邮箱" prop="email">
            	<u-input :border="border" placeholder="请输入正确邮箱" v-model="model.email" type="text"></u-input>
            </u-form-item>
			<u-form-item :label-position="labelPosition" label="手机号码" prop="phone" label-width="150">
				<u-input :border="border" placeholder="请输入手机号" v-model="model.phone" type="number"></u-input>
			</u-form-item>
			<!-- 此处switch的slot为right，如果不填写slot名，也即<u-switch v-model="model.remember"></u-switch>，将会左对齐 -->
<!-- 			<u-form-item :label-position="labelPosition" label="上传图片" prop="photo" label-width="150">
				<u-upload width="160" height="160"></u-upload>
			</u-form-item> -->
		</u-form>
		<view class="agreement">
			<u-checkbox v-model="check" @change="checkboxChange"></u-checkbox>
			<view class="agreement-text">
				勾选代表同意用户协议
			</view>
		</view>
		<u-button @click="submit">提交</u-button>
		<u-action-sheet :list="actionSheetList" v-model="actionSheetShow" @click="actionSheetCallback"></u-action-sheet>
	</view>
    </view>
</template>

<script>
    import { alreadyUsername,register } from "@/api/login.js"
export default {
	data() {
		let that = this;
		return {
            background: {
                backgroundImage: 'linear-gradient(45deg, rgb(255, 40, 0), rgb(147, 0, 0))'
            },
			model: {
				name: '',
				sex: '',
				agreement: false,
				phone: '',
                email:'',
				password: '',
				rePassword: '',
				remember: false,
				// photo: ''
			},
			rules: {
				name: [
					{
						required: true,
						message: '请输入姓名',
						trigger: 'blur' ,
					},
					{
						min: 2,
						max: 5,
						message: '姓名长度在2到5个字符',
						trigger: ['change','blur'],
					},
					
					// 异步验证，用途：比如用户注册时输入完账号，后端检查账号是否已存在
					{
						trigger: ['blur'],
						// 异步验证需要通过调用callback()，并且在里面抛出new Error()
						// 抛出的内容为需要提示的信息，和其他方式的message属性的提示一样
						asyncValidator: (rule, value, callback) => {
                            alreadyUsername({
                                userName: value
                            }).then(function(res){
                                if(res.data.code==200){
                                    callback();
                                }
                                else{
                                    callback(new Error('用户名重复'));
                                }
                            })
							
						},
					}
				],
				sex: [
					{
						required: true,
						message: '请选择性别',
						trigger: 'change'
					},
				],
                email: [
                    {
                    	required: true,
                    	message: '请输入邮箱',
                    	trigger: ['change','blur'],
                    },
                    {
                    	validator: (rule, value, callback) => {
                    		// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
                    		return this.$u.test.email(value);
                    	},
                    	message: '邮箱号不正确',
                    	// 触发器可以同时用blur和change，二者之间用英文逗号隔开
                    	trigger: ['change','blur'],
                    }
                ],
				phone: [
					{
						required: true,
						message: '请输入手机号',
						trigger: ['change','blur'],
					},
					{
						validator: (rule, value, callback) => {
							// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
							return this.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						// 触发器可以同时用blur和change，二者之间用英文逗号隔开
						trigger: ['change','blur'],
					}
				],
				password: [
					{
						required: true,
						message: '请输入密码',
						trigger: ['change','blur'],
					},
					{
						// 正则不能含有两边的引号
						pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]+\S{5,12}$/,
						message: '需同时含有字母和数字，长度在6-12之间',
						trigger: ['change','blur'],
					}
				],
				rePassword: [
					{
						required: true,
						message: '请重新输入密码',
						trigger: ['change','blur'],
					},
					{
						validator: (rule, value, callback) => {
							return value === this.model.password;
						},
						message: '两次输入的密码不相等',
						trigger: ['change','blur'],
					}
				],
			},
			
			border: false,
			check: false,
			selectStatus: 'close',
			actionSheetList: [
				{
					text: '男'
				},
				{
					text: '女'
				},

			],
            actionSheetShow: false,
            labelPosition: 'left',
            codeTips: '',
            errorType: ['message'],
		};
	},
	onLoad() {

	},
	computed: {
		borderCurrent() {
			return this.border ? 0 : 1;
		}
	},
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	methods: {
		submit() {
            const _this =this
            let sex = 1
            if(this.model.sex=='男'){
                sex=1
            }
             else{
                 sex=2
             }
              
            const user = {
                userName: this.model.name,
                email: this.model.email,
                sex: sex,
                phoneNumber: this.model.phone,
                password: this.model.rePassword,
            }
			this.$refs.uForm.validate(valid => {
				if (valid) {
					if(!this.model.agreement) return this.$u.toast('请勾选协议');
                    register(user).then(function(res){
                        console.log(res.data)
                        if(res.data.code==200){
                        uni.showLoading({
                                title: '注册成功！'
                            })
                            setTimeout(function() {
                                uni.hideLoading();
                                uni.reLaunch({
                                    url: '/pages/login/index'
                                })
                            }, 1500);
                                
                            }else{
                                uni.showLoading({
                                        title: '注册失败！请重试'
                                    })
                                    setTimeout(function() {
                                        uni.hideLoading();
                                    }, 1500);
                            }
                        
                    })
                    // console.log(this.model)
					// console.log('验证通过');
				} else {
					console.log('验证失败');
				}
			});
		},
		// 点击actionSheet回调
		actionSheetCallback(index) {
			uni.hideKeyboard();
			this.model.sex = this.actionSheetList[index].text;
		},
		
		// 勾选版权协议
		checkboxChange(e) {
			this.model.agreement = e.value;
		},
		
	}
};
</script>

<style scoped lang="scss">
.wrap {
	padding: 30rpx;
}

.agreement {
	display: flex;
	align-items: center;
	margin: 40rpx 0;

	.agreement-text {
		padding-left: 8rpx;
		color: $u-tips-color;
	}
}
</style>